package com.csc.usermanagement.admin;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;

/**
 * Servlet implementation class AddNewUserServlet
 */
@WebServlet("/AddNewUser")
public class AddNewUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddNewUserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Get parameters from user submit.
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String type = request.getParameter("type");
		java.util.Date utilDate = new java.util.Date();
		Date date = new Date(utilDate.getTime());

		// Prepare SQL statements.
		String querySQL = "select * from user where UserName = ?";
		String addSQL = "insert into user values('" + username + "', '"
				+ password + "', '" + type + "', '"  + date + "')";

		// Prepare connection to the database.
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet resultSet = null;
		
		try {
			conn = UserManagementDbConnector.getConnection();
			stmt = conn.prepareStatement(querySQL);
			stmt.setString(1, username);
			resultSet = stmt.executeQuery();
			// Account existed.
			if (resultSet.next()) {
				request.setAttribute("msg", "There is an account with this username! Please input another username");
				request.getRequestDispatcher("/AddNewUser.jsp").forward(request, response);
			} else {
				// Add new user to the database.
				stmt = conn.prepareStatement(addSQL);
				stmt.executeUpdate(addSQL);
				request.setAttribute("msg", "Successfully created an account!");
				request.getRequestDispatcher("/ListAllUsers").forward(request, response);
			}
			

			resultSet.close();
			stmt.close();
			conn.close(); 
		} catch (SQLException se) {
			se.printStackTrace();
		}
		
	}

}
